﻿using System;
using System.Collections.Generic;
using System.Linq;
using System.Web;
using System.Web.UI;
using System.Web.UI.WebControls;
using TMDT.BusinessLogic;
using TMDT.BusinessObjects;
using TMDT.Web.UI.Commons;

namespace TMDT.Web.UI.Controls
{
    public partial class DangKyControl : System.Web.UI.UserControl
    {
        protected void Page_Load(object sender, EventArgs e)
        {
            if(Session["User"] != null)
            {
                Response.Redirect("SanPham.aspx");
            }
            if(!IsPostBack)
            {
                LoadData();
            }
        }

        private void LoadData()
        {
            var service = new TinhThanhPhoManager();
            ddlTinhThanhPho.LoadDataSource(service.GetTinhThanhPho(),"TenTinhThanhPho","IDTinhThanhPho");
        }

        protected void btnDangKy_Click(object sender, EventArgs e)
        {
            if(!Page.IsValid)
                return;
            var service = new TaiKhoanManager();
            if (!service.IsExists(txtTenDangNhap.Text))
            {
                var loaiTaiKhoan = new LoaiTaiKhoanManager();
                bool bGioiTinh = ddlGioiTinh.SelectedIndex == 0;
                var entity = new TaiKhoan
                                 {
                                     IDTaiKhoan = Guid.NewGuid(),
                                     IDLoaiTaiKhoan = loaiTaiKhoan.GetLoaiTaiKhoanByQuyen(2).IDLoaiTaiKhoan,
                                     CMND = txtCMND.Text,
                                     DienThoai = txtDienThoai.Text,
                                     Email = txtEmail.Text,
                                     GioiTinh = bGioiTinh,
                                     HoTen = txtHoTen.Text,
                                     IDTinhThanhPho = new Guid(ddlTinhThanhPho.SelectedValue),
                                     MatKhau = txtMatKhau.Text,
                                     NgayDangKy = DateTime.Now,
                                     NgayKetThuc = DateTime.Now.AddDays(7),
                                     TenDangNhap = txtTenDangNhap.Text,
                                     NgaySinh = DateTime.Parse(txtNgaySinh.Text)
                                 };
                service.Add(entity);
                Session["User"] = txtTenDangNhap.Text;
                Response.Redirect("SanPham.aspx");
            }
            else
            {
                lblError.Text = "Tên đăng nhập đã tồn tại";
            }
        }

        protected void btnLamMoi_Click(object sender, EventArgs e)
        {
            Response.Redirect("DangKy.aspx");
        }
    }
}